#include <iostream>
#include <bsondoc.h>
#include <bsonclientpool.h>
#include "json/json.h"

using namespace std;
BsonClientPool* ppool = NULL;
ScopedBsonClient *pclient = NULL;

void insert()
{
    bool bret = true;
    cout<<"inserting"<<endl;
    BsonDoc* pinsert = new BsonDoc();
    BSONDOC_APPEND(pinsert->doc(),"hello","world");
    bret = pclient->insertOne("test","mycoll",pinsert->doc());
    delete pinsert;
    if ( !bret )
    {
        cout<<"insert failed"<<endl;
    }
    cout<<"inserted"<<endl;
}

void find()
{
    string tmp;
    BsonDoc* pfind  = NULL;
    cout<<"finding"<<endl;
    pfind = new BsonDoc();
    BSONDOC_APPEND(pfind->doc(),"hello","world");
    cout<<"req json:"<<BsonDoc::toJson(pfind->doc())<<endl;
    tmp = pclient->find("test","mycoll",pfind->doc());
    delete pfind;
    cout<<"found:"<<tmp<<endl;
}

void update()
{
    bool bret = true;
    BsonDoc* pupdate= NULL;
    BsonDoc* pquery = NULL;
    cout<<"updating"<<endl;
    pupdate = new BsonDoc();
    BSONDOC_APPEND(pupdate->doc(),"$set","{","test","aaa","}");
    pquery = new BsonDoc();
    BSONDOC_APPEND(pquery->doc(),"hello","world");

    bret = pclient->updateOne("test","mycoll",pquery->doc(),pupdate->doc());
    delete pupdate;
    delete pquery;
    if ( !bret )
    {
        cout<<"update failed:"<<endl;
        return;
    }
    cout<<"updated"<<endl;
    
}

void del()
{
    bool bret = true;
    BsonDoc* pdel   = NULL;
    cout<<"deleting"<<endl;
    pdel = new BsonDoc();
    BSONDOC_APPEND(pdel->doc(),"test","aaa");
    bret = pclient->deleteOne("test","mycoll",pdel->doc());
    delete pdel;
    if ( !bret )
    {
        cout<<"delete failed:"<<endl;
        return;
    }
    cout<<"deleted"<<endl;

}

int main(int argc, char* argv[])
{
    if ( argc != 2 )
    {
        cout<<"usage: ./test insert/find/update/del"<<endl;
        return 0;
    }
    
    string uri("mongodb://localhost:27017");
    ppool = new BsonClientPool(uri);
    pclient = new ScopedBsonClient(*ppool);

    string oper(argv[1]);
    if (oper == "insert" )
    {
        insert();
    }
    else if (oper == "find")
    {
        find();
    }
    else if (oper == "update")
    {
        update();
    }
    else if (oper == "del")
    {
        del();
    }

    delete pclient;
    delete ppool;
    BsonClientPool::release();
    return 0;
}





